package com.cwj.os.coursedesgin.bashor;

import com.sun.source.tree.Tree;

import java.io.File;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

// 文件字典树结构

public class FileTrie {
    TreeNode faTreeNode;//指向所属目录节点
    TireNode<MyFile> root = new TireNode<>(false);//字典树的根节点

    public FileTrie(TreeNode faTree) {
        this.faTreeNode = faTree;
    }

//    插入一个文件
    public Boolean insert(MyFile file, Boolean isReplace) {
        String str = file.getName();
        TireNode<MyFile> tmp = this.root;
        for (int i = 0; i < str.length(); i++) {
            assert tmp != null;
            Character cc = str.charAt(i);
            if (((tmp.getSon().get(cc)) != null)) {
                tmp = tmp.getSon().get(cc);
            } else {
                tmp.getSon().put(cc, new TireNode<MyFile>());
                i--;
            }
        }

        if (!tmp.getHas() || isReplace) tmp.setFile(file);

        return !tmp.getHas();
    }

//    查找一个文件
    public TireNode<MyFile> find(String str) {
        TireNode<MyFile> tmp = this.root;
        for (int i = 0; i < str.length(); i++) {
            assert tmp != null;
            Character cc = str.charAt(i);
            if (((tmp.getSon().get(cc)) != null)) {
                tmp = (TireNode<MyFile>) tmp.getSon().get(cc);
            } else return null;
        }
        return tmp;
    }

//  一次一个文件
    public boolean remove(String str) {
        final TireNode<MyFile> tireNode = this.find(str);
        if (tireNode == null) return false;
        tireNode.setFile(null);
        tireNode.setHas(false);
        return true;
    }

    public ArrayList<MyFile> getFullFile() {
        ArrayList<MyFile> files = new ArrayList<>();
        this.getFull(this.root,new StringBuilder(),files);
        return files;
    }


    private void getFull(TireNode<MyFile> nn,StringBuilder sb, ArrayList<MyFile> list) {

        if (nn.getHas()) {list.add(nn.getFile()); }

        final HashMap<Character, TireNode> son = nn.getSon();

        son.forEach((k,v)->{
            sb.append(k);
            this.getFull(v,sb,list);
            sb.deleteCharAt(sb.length()-1);
        });


    }


}

//  字典树节点结构
class  TireNode <T> {

    Boolean isHas;//该节点是否有文件
    T file;//文件
    HashMap<Character, TireNode> son = new HashMap<>();//子节点

    public TireNode(Boolean isHas) {
        this.isHas = isHas;
        this.file = null;
    }

    public TireNode() {
        this(false);
    }

    public Boolean getHas() {
        return isHas;
    }

    public void setHas(Boolean has) {
        isHas = has;
    }

    public T getFile() {
        return file;
    }

    public void setFile(T file) {
        this.file = file;
        this.isHas = file!=null;
    }

    public HashMap<Character, TireNode> getSon() {
        return son;
    }

    public void setSon(HashMap<Character, TireNode> son) {
        this.son = son;
    }

}
